using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using OrbitOne.CRMLyncInfoDashboard.CRM.Organization;
using OrbitOne.CRMLyncInfoDashboard.CRM.OrganizationData;

namespace OrbitOne.CRMLyncInfoDashboard.CRM.OData
{
    public class EntitytMetadataModel
    {
        protected readonly EntityMetadata m_entityMetadata;

        public string ImageLocation
        {
            get {

                if (m_entityMetadata.LogicalName.Equals(typeof(Account).Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return GetImage("ico_fhe_1.png");
                }

                if (m_entityMetadata.LogicalName.Equals(typeof(Contact).Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return GetImage("ico_fhe_2.png");
                }
                
                if (m_entityMetadata.LogicalName.Equals(typeof(Lead).Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return GetImage("ico_fhe_4.png");
                }
                return "";
            }
        }

        public string LogicalName
        {
            get { return m_entityMetadata.LogicalName; }
        }

        private static string GetImage(string imageName)
        {
            return string.Format("{0}/{1}", "../Images", imageName);
        }

        public EntitytMetadataModel(EntityMetadata entityMetadata)
        {
            m_entityMetadata = entityMetadata;
        }

        public string DisplayCollectionName
        {
            get { return m_entityMetadata.DisplayCollectionName.UserLocalizedLabel.Label; }
        }

        public string DisplayName
        {
            get { return m_entityMetadata.DisplayName.UserLocalizedLabel.Label; }
        }

        public string this[string internalAttributeName]
        {
            get
            {
                var attribute = Attributes.FirstOrDefault(
                    a => a.SchemaName.Equals(internalAttributeName, StringComparison.InvariantCultureIgnoreCase));
                if(attribute == null)
                {
                    return "";
                }

                var localizedLabels = attribute.DisplayName.LocalizedLabels;
                return localizedLabels != null && localizedLabels.Any()
                           ? localizedLabels[0].Label
                           : "";
            }
        }

        public IList<AttributeMetadata> Attributes
        {
            get { return m_entityMetadata.Attributes; }
        }
    }
}